<?

class admin_util_acl extends Zend_Acl {
	/**
	 *
	 * @var admin_model_user
	 */
	var $user;
	/**
	 * 
	 *
	 * @var admin_model_role
	 */
	var $role;
	/**
	 * 
	 *
	 * @var admin_model_resource
	 */
	var $resource;
	
	public function __construct(){
		$this->user = Model::factory('admin_model_user');
		$this->role = Model::factory('admin_model_role');
		$this->resource = Model::factory('admin_model_resource');
		$this->initializeGuest();
		$this->initializeResources();
		$this->initializeRoles();
		$this->initializeUsers();
		$this->allow('admin');
		
	}
	
	public function initializeGuest(){
		$this->addRole(new Zend_Acl_Role('__guest'));
		if(!$this->has('admin_user_no_priv')){
			$this->add(new Zend_Acl_Resource('admin_user_no_priv'));
		}
		if(!$this->has('admin_login_login_form')){
			$this->add(new Zend_Acl_Resource('admin_login_login_form'));
		}
		if(!$this->has('admin_login_login')){
			$this->add(new Zend_Acl_Resource('admin_login_login'));
		}
		if(!$this->has('admin_error_show')){
			$this->add(new Zend_Acl_Resource('admin_error_show'));
		}
		$this->allow('__guest', 'admin_user_no_priv');
		$this->allow('__guest', 'admin_login_login_form');
		$this->allow('__guest', 'admin_login_login');
		$this->allow('__guest', 'admin_error_show');
	}
	
	public function initializeResources(){
		$rows = $this->resource->selectList();
		foreach($rows as $row){
			$r = new Zend_Acl_Resource($row['app'] . '_' . $row['controller'] . '_' . $row['action']);
			if(!$this->has($r))
			$this->add($r);
		}
	}
	
	public function initializeRoles(){
		$rows = $this->role->selectList();
		foreach($rows as $row){
			$role = new Zend_Acl_Role($row['role']);
			$this->addRole($role);
			$privs = $this->role->selectRolePriv($row['id']);
			foreach($privs as $priv){
				$this->allow($role, $priv['resource']);
			}
		}
	}
	
	public function initializeUsers(){
		$users = $this->user->selectList();
		foreach($users as $user){
			$parentRoles = array();
			$roles = $this->user->selectUserRole($user['id']);
			foreach($roles as $role){
				array_push($parentRoles, $role['role']);
			}
			array_push($parentRoles, '__guest');
			$role = new Zend_Acl_Role('user_'.$user['id']);
			$this->addRole($role, $parentRoles);
			$privs = $this->user->selectUserPriv($user['id']);
			foreach($privs as $priv){
				$this->allow($role, $priv['resource']);
			}
			
		}
	}
	
	/**
	 *
	 * @param id $uid
	 * @param AdminController $controller
	 */
	public function isAllowUser($uid, $resource){
//		$resource = $controller->app."_".$controller->controller."_".$controller->action;
		if(!$this->has($resource)){
			$this->add(new Zend_Acl_Resource($resource));
		}
		if(!$this->hasRole('user_'.$uid)){
			$this->addRole(new Zend_Acl_Role('user_'.$uid), '__guest');
		}
		return $this->isAllowed('user_'.$uid, $resource);
	}
}